﻿using I_Archives.Domains.DTO;
using I_Archives.Infrastructure.Interface;
using I_Archives.Read.API.Application.Command;
using MediatR;

namespace I_Archives.Read.API.Application.CommandHandler
{
    public class ArvchivesReadGenealogyCommandHandlere : IRequestHandler<ArchivesReadGenealogyCommand, SheepGenealogy>
    {
        private readonly IArchivesRepository _archivesRepository;

        public ArvchivesReadGenealogyCommandHandlere(IArchivesRepository archivesRepository)
        {
            _archivesRepository = archivesRepository;
        }

        public async Task<SheepGenealogy> Handle(ArchivesReadGenealogyCommand request, CancellationToken cancellationToken)
        {
            var archivesInfo = await _archivesRepository.GetByFuncAsync(x => x.Id.Equals(request.Id));
            var sheepGenealogy = new SheepGenealogy();
            if(archivesInfo != null)
            {
                sheepGenealogy.EarNumber = archivesInfo.EarNnumber;
                sheepGenealogy.FatherEarNumber = archivesInfo.FatherEarNumber;
                sheepGenealogy.MotherEarNumber = archivesInfo.MotherEarNumber;
                var fatherArchivesInfo = await _archivesRepository.GetByFuncAsync(x => x.EarNnumber.Equals(archivesInfo.FatherEarNumber));
                if (fatherArchivesInfo != null)
                {
                    sheepGenealogy.GrandFatherEarNumber = fatherArchivesInfo.FatherEarNumber;
                    sheepGenealogy.GrandMotherEarNumber = fatherArchivesInfo.MotherEarNumber;
                }
                var motherArchivesInfo = await _archivesRepository.GetByFuncAsync(x => x.EarNnumber.Equals(archivesInfo.MotherEarNumber));
                if (motherArchivesInfo != null)
                {
                    sheepGenealogy.GrandPaFatherEarNumber = motherArchivesInfo.FatherEarNumber;
                    sheepGenealogy.GrandPaMotherEarNumber = motherArchivesInfo.MotherEarNumber;
                };
            }
            return sheepGenealogy;
        }
    }
}
